
//
//  PeerList.m
//  安好
//
//  Created by lianchuang on 14/10/30.
//  Copyright (c) 2014年 冯凯. All rights reserved.
//

#import "PeerList.h"

@implementation PeerList

- (id)initWithUid:(NSString *)uid AndMyuid:(NSString *)myuid AndDate:(NSString *)date AndDateline:(NSString *)dateline AndMessage:(NSString *)message AndQid:(NSString *)qid AndType:(NSString *)type AndNoread:(NSString *)noread AndUsername:(NSString *)username AndMethod:(NSString *)method And:(NSString *)success
{
    if (self=[super init]) {
        self.qid=qid;
        self.myuid=myuid;
        self.date=date;
        self.dateline=dateline;
        self.message=message;
        self.type=type;
        self.uid=uid;
        self.noread=noread;
        self.username=username;
        self.method=method;
        self.success=success;
    }
    return self;
}
/**
 *  同行或者俩客户端之间聊天信息
 *
 *  @param message 聊天的message（NSDictionary类型的）
 *
 *  @return 聊天信息是否存入数据库成功
 */
+(BOOL)updatePeerList:(id)message withReadStatus:(NSString *)readStatus withSuccess:(NSString *)success withMessageDirection:(NSString *)messageDirection
{
    FMDatabase *db=[MyFMDB openDB];
    NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
    NSString * uid1 = [userDefaults objectForKey:@"SelfUidKey"];
    NSDictionary *dict = [YXJSON dictionaryOrArrayWithJSONSString:message];
    if ([self isExistPeerItem:dict AndDb:db]) {
        
        NSString *noread;

        //查看列表的阅读状态
        NSString * readsql = [NSString stringWithFormat:@"select noread from PeerList where uid = ?"];
        FMResultSet * rs = [db executeQuery:readsql, [dict valueForKey:@"uid"]];
        if([rs next])
        {
            noread=[rs stringForColumn:@"noread"];
        }

        NSString * sql = [NSString stringWithFormat:@"update PeerList set date = ?, dateline = ?, message = ?, qid = ?, type = ?, noread = ?, username = ? ,method= ? ,success=? where uid = ? and myuid = ?"];
        NSString *uid=[dict valueForKey:@"uid"];
        NSString *myuid=[NSString stringWithFormat:@"%@",uid1];
        NSString *date=@"";
        NSString *dateline=[dict valueForKey:@"dateline"];
        NSString *type=[dict valueForKey:@"type"];
        NSString *qid=[dict valueForKey:@"qid"];
        NSString *username=[dict valueForKey:@"username"];
        
        if ([messageDirection isEqualToString:@"1"]&&[noread isEqualToString:@"-1"]) {
            noread=@"-1";
        }else if([messageDirection isEqualToString:@"1"]&&[noread isEqualToString:@"0"])
        {
            noread=@"0";
        }else if ([messageDirection isEqualToString:@"2"])
        {
            noread=readStatus;
        }
        NSString *method=[dict valueForKey:@"method"];
        NSString *chatMessage;
        //    NSInteger messageType;
        if ([[dict valueForKey:@"message"] length] > 0) {
            //        messageType = 1;
            chatMessage=[dict valueForKey:@"message"];
        } else if ([[dict valueForKey:@"pic"] length] > 0) {
            //        messageType = 2;
            chatMessage = @"[图片]";
        } else {
            //        messageType = 3;
            chatMessage = @"[语音]";
        }
        NSString *successType=success;
        BOOL successM= [db executeUpdate:sql,date,dateline,chatMessage,qid,type,noread,username,method,successType,uid,myuid];
        return successM;
        
    }else
    {
        NSString * sql = [NSString stringWithFormat:@"insert into PeerList (uid, myuid, date, dateline, message, type, qid, username,noread,method,success) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"];
        NSString *uid=[dict valueForKey:@"uid"];
        NSString *myuid=uid1;
        NSString *date=@"";
        NSString *dateline=[dict valueForKey:@"dateline"];
        NSString *type=[dict valueForKey:@"type"];
        NSString *qid=[dict valueForKey:@"qid"];
        NSString *username=[dict valueForKey:@"username"];
        NSString *noread=[NSString stringWithFormat:@"%@",readStatus];
        NSString *method=[dict valueForKey:@"method"];
        NSString *chatMessage;
        //    NSInteger messageType;
        if ([[dict valueForKey:@"message"] length] > 0) {
            //        messageType = 1;
            chatMessage=[dict valueForKey:@"message"];
        } else if ([[dict valueForKey:@"pic"] length] > 0) {
            //        messageType = 2;
            chatMessage = @"[图片]";
        } else {
            //        messageType = 3;
            chatMessage = @"[语音]";
        }
        NSString *successType=success;
        BOOL successM= [db executeUpdate:sql,uid,myuid,date,dateline,chatMessage,type,qid,username,noread,method,successType];
        return successM;
    }
}
/**
 *  根据同行的uid，设置未读信息个数
 *
 *  @param uid 同行的uid（唯一标识）
 *
 *  @return 重置未读信息个数是否成功
 */
+(BOOL)resetUnreadCountWithUid:(NSString *)uid
{
    FMDatabase *db=[MyFMDB openDB];

    NSString * sql = [NSString stringWithFormat:@"update PeerList set noread = 0 where uid = %@", uid];
    BOOL success=[db executeUpdate:sql];
    [db close];
    return success;
}
/**
 *  根据用户uid判断该消息是否存在，若存在，就更新表里内容；若不存在，就往数据库里插入一条数据
 *
 *  @param dict     消息内容信息
 *  @param dataBase 当前数据库
 *
 *  @return Yes or no
 */
+(BOOL)isExistPeerItem:(NSDictionary *)dict AndDb:(FMDatabase *)dataBase
{
    NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
    NSString * uid = [userDefaults objectForKey:@"SelfUidKey"];
    NSString * sql = [NSString stringWithFormat:@"select uid from PeerList where uid = ? and myuid = %@", uid];
    FMResultSet * rs = [dataBase executeQuery:sql,[dict valueForKey:@"uid"]];
    if([rs next])
    {
        // 如果有值
        return YES;
    }
    return NO;
}
/**
 *  更新聊天状态，是否发送成功
 *
 *  @param uid 普通用户端的用户唯一标识id
 *
 *  @return yes or no
 */
- (BOOL)resetPeerListSuccessStatus:(NSString *)uid
{
    FMDatabase *db=[MyFMDB openDB];
    
    NSString * sql = [NSString stringWithFormat:@"update PeerList set success = YES where uid = %@", uid];
    BOOL success=[db executeUpdate:sql];
    [db close];
    return success;
}
/**
 *  获取同行聊天列表
 *
 *  @return 同行列表数组
 */
+(NSMutableArray *)readAllPeerListItem;
{
    FMDatabase *db=[MyFMDB openDB];
    NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
    NSString * uid = [userDefaults objectForKey:@"SelfUidKey"];
    NSString * sql = [NSString stringWithFormat:@"select * from PeerList where myuid = %@ order by dateline desc", uid];
    FMResultSet *rs=[db executeQuery:sql];
    NSMutableArray *array=[[NSMutableArray alloc]init];
    while ([rs next]) {
//        NSDictionary *rs=[set resultDictionary];
        PeerList * peerList = [[PeerList alloc] init];
        peerList.uid = [rs stringForColumn:@"uid"];
        peerList.date = [rs stringForColumn:@"date"];
        peerList.dateline = [rs stringForColumn:@"dateline"];
        peerList.message = [rs stringForColumn:@"message"];
        peerList.qid = [rs stringForColumn:@"qid"];
        peerList.type = [rs stringForColumn:@"type"];
        peerList.noread = [rs stringForColumn:@"noread"];
        peerList.username = [rs stringForColumn:@"username"];
        peerList.method = [rs stringForColumn:@"method"];
        [array addObject:peerList];
    }
    [db close];
    return array;
}
/**
 *  删除一条同行之间的聊天
 *
 *  @param uid 对方的uid
 *
 *  @return 删除是否成功
 */
+(BOOL)deleteConsultListWithUid:(NSString *)uid
{
    FMDatabase *db=[MyFMDB openDB];
    NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
    NSString * myuid = [userDefaults objectForKey:@"SelfUidKey"];
    BOOL success=[db executeUpdate:@"delete from PeerList where uid=? and myuid=?",uid,myuid];
    [db close];
    return success;
}
/**
 *  安好消息，返回未读的个数
 *
 *  @return 未读个数
 */
+(int)readUnreadCount
{
    int count=0;
    FMDatabase *db=[MyFMDB openDB];
    NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
    NSString * uid = [userDefaults objectForKey:@"SelfUidKey"];
    NSString * sql = [NSString stringWithFormat:@"select * from PeerList where myuid = %@ and noread=1", uid];
    FMResultSet *rs=[db executeQuery:sql];
    while ([rs next]) {
       count =count+1;
    }
    [db close];
    return count;
}
/**
 *  获取最后一条同行聊天的最后一条（按照时间排序，即离现在时间最近的一条）；
 *
 *  @return 返回peerlist类型的数据；
 */
+(NSMutableArray *)getTheLastOne
{
    FMDatabase *db=[MyFMDB openDB];
    NSUserDefaults *userDefaults= [NSUserDefaults standardUserDefaults];
    NSString * uid = [userDefaults objectForKey:@"SelfUidKey"];
    NSString * sql = [NSString stringWithFormat:@"select * from PeerList where myuid = %@ order by dateline desc  limit 0,1", uid];
    FMResultSet *rs=[db executeQuery:sql];
    NSMutableArray *array=[[NSMutableArray alloc]init];
    while ([rs next]) {
        //        NSDictionary *rs=[set resultDictionary];
        PeerList * peerList = [[PeerList alloc] init];
        peerList.uid = [rs stringForColumn:@"uid"];
        peerList.date = [rs stringForColumn:@"date"];
        peerList.dateline = [rs stringForColumn:@"dateline"];
        peerList.message = [rs stringForColumn:@"message"];
        peerList.qid = [rs stringForColumn:@"qid"];
        peerList.type = [rs stringForColumn:@"type"];
        peerList.noread = [rs stringForColumn:@"noread"];
        peerList.username = [rs stringForColumn:@"username"];
        peerList.method = [rs stringForColumn:@"method"];
        [array addObject:peerList];
    }
    [db close];
    return array;
}
@end
